package com.hzeport.bgs22emduty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzeport.bgs22emduty.config.login.LoginCompoentService;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.dto.ParamHolidaysDTO;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.outbound.ParamHolidaysRepository;
import com.hzeport.bgs22emduty.vo.ParamHolidays.ParamHolidaysSaveVO;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import com.hzeport.bgs22emduty.common.base.BaseServiceImpl;
import com.hzeport.bgs22emduty.entity.ParamHolidays;
import com.hzeport.bgs22emduty.outbound.db.ParamHolidaysRepositoryImpl;
import com.hzeport.bgs22emduty.service.ParamHolidaysService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 假期年度：
 * 说明假期使用的年度
 * <p>
 * 假期日期：
 * 年度假期的具体日期，yyyy-MM-dd
 *
 * @author code generator
 * @date 2022-12-02 11:21:59
 */
@Service
@Slf4j
public class ParamHolidaysServiceImpl extends BaseServiceImpl< ParamHolidaysRepositoryImpl, ParamHolidays > implements ParamHolidaysService {

    @Resource
    private ParamHolidaysRepository paramHolidaysRepository;
    @Resource
    private LoginCompoentService loginCompoentService;


    /*查询*/
    @Override
    public BaseResult< PageInfo< ParamHolidays > > list( ParamHolidaysDTO paramHolidaysDTO ) throws Exception {
        UserInfoDetailVO userInfoDetailVO=loginCompoentService.getUserInfo();
        if ( paramHolidaysDTO.getHolidayYear() == null ) {
            PageHelper.startPage( paramHolidaysDTO.getPageNum() , paramHolidaysDTO.getPageSize() );
            List< ParamHolidays > list =
                    paramHolidaysRepository.list( new LambdaQueryWrapper< ParamHolidays >()
                            .eq(ParamHolidays::getCustomId,userInfoDetailVO.getCustomscode()).orderByAsc( ParamHolidays::getHolidayDate ) );
            PageInfo< ParamHolidays > pageInfo = new PageInfo<>( list );
            return BaseResult.ok( pageInfo , "查询成功" );
        }
        else {
            PageHelper.startPage( paramHolidaysDTO.getPageNum() , paramHolidaysDTO.getPageSize() );
            List< ParamHolidays > list =
                    paramHolidaysRepository.list( new LambdaQueryWrapper< ParamHolidays >().eq(ParamHolidays::getCustomId,userInfoDetailVO.getCustomscode()).eq( ParamHolidays::getHolidayYear , paramHolidaysDTO.getHolidayYear() ).orderByDesc( ParamHolidays::getHolidayDate ) );
            if ( CollectionUtils.isEmpty( list ) ) {
                throw new Exception( paramHolidaysDTO.getHolidayYear() + ",此年度为空请查看是否初始化" );
            }
            PageInfo< ParamHolidays > pageInfo = new PageInfo<>( list );
            return BaseResult.ok( pageInfo , "查询成功" );
        }
    }

    //删除
    @Override
    public BaseResult delete( String id ) {
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        ParamHolidays paramHolidays = new ParamHolidays();
        paramHolidays.setUpdateBy( userInfoDetailVO.getUserId() );
        paramHolidays.setUpdateTime( LocalDateTime.now() );
        paramHolidays.setDelFlag( DeleteFlagEnum.IS_DELETE.getValue() );
        paramHolidaysRepository.remove( new LambdaQueryWrapper< ParamHolidays >().eq( ParamHolidays::getId , id ) );
        return BaseResult.ok( null , "删除成功" );
    }

    //    //初始化
    //    @Override
    //    public  BaseResult<List<ParamHolidays>> init(ParamHolidaysDTO paramHolidaysDTO) throws Exception {
    //        UserInfoDetailVO userInfoDetailVO=loginCompoentService.getUserInfo();
    //        List<ParamHolidays> paramHolidaysList=paramHolidaysRepository.list(
    //                new LambdaQueryWrapper<ParamHolidays>().eq(ParamHolidays::getHolidayYear,paramHolidaysDTO
    //                .getHolidayYear()));
    //        List<ParamHolidays> paramHolidaysListList=new ArrayList<>();
    //        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
    //        if(CollectionUtils.isEmpty(paramHolidaysList)){
    //            int year= Math.toIntExact(paramHolidaysDTO.getHolidayYear());
    //            int i=1;
    //            GregorianCalendar calendar = new GregorianCalendar(year,0,1);
    //            while (calendar.get(Calendar.YEAR) < year+1){
    //                calendar.set(Calendar.WEEK_OF_YEAR,i++);
    //                calendar.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);
    //                //周日
    //                if(calendar.get(Calendar.YEAR) == year){
    //                    ParamHolidays paramHolidays = new ParamHolidays();
    //                    paramHolidays.setHolidayYear(paramHolidaysDTO.getHolidayYear());
    //                    paramHolidays.setHolidayDate(LocalDate.parse(simple.format(calendar.getTime())));
    //                    paramHolidays.setCreateTime(LocalDateTime.now());
    //                    paramHolidays.setCreateBy(userInfoDetailVO.getUserId());
    //                    paramHolidays.setUpdateBy(userInfoDetailVO.getUserId());
    //                    paramHolidays.setHolidayDept(userInfoDetailVO.getCustomsName());
    //                    paramHolidays.setHolidayType(HolidaysEnum.HOLIDAY.getValue());
    //                    paramHolidays.setUpdateTime(LocalDateTime.now());
    //                    paramHolidays.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
    //                    paramHolidays.setRemark("星期日");
    //                    paramHolidaysListList.add(paramHolidays);
    //                }
    //                //周六
    //                calendar.set(Calendar.DAY_OF_WEEK,Calendar.SATURDAY);
    //                if(calendar.get(Calendar.YEAR) == year){
    //                    ParamHolidays paramHolidays = new ParamHolidays();
    //                    paramHolidays.setHolidayYear(paramHolidaysDTO.getHolidayYear());
    //                    paramHolidays.setHolidayDate(LocalDate.parse(simple.format(calendar.getTime())));
    //                    paramHolidays.setCreateTime(LocalDateTime.now());
    //                    paramHolidays.setCreateBy(userInfoDetailVO.getUserId());
    //                    paramHolidays.setUpdateBy(userInfoDetailVO.getUserId());
    //                    paramHolidays.setHolidayDept(userInfoDetailVO.getCustomsName());
    //                    paramHolidays.setHolidayType(HolidaysEnum.HOLIDAY.getValue());
    //                    paramHolidays.setUpdateTime(LocalDateTime.now());
    //                    paramHolidays.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
    //                    paramHolidays.setRemark("星期六");
    //                    paramHolidaysListList.add(paramHolidays);
    //                }
    //            }
    //        }else {
    //            throw new Exception(paramHolidaysDTO.getHolidayYear()+"年节假日已经初始化，不可重复操作");
    //        }
    //        paramHolidaysRepository.saveBatch(paramHolidaysListList);
    //        return BaseResult.ok(null,"初始化成功");
    //    }


    @Override
    public BaseResult saveData( ParamHolidaysSaveVO paramHolidaysSaveVO ) {
        List< ParamHolidays > paramHolidaysList = new ArrayList<>();
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        //获取两个日期之间的所有日期
        List< LocalDate > localDates = getLocalDate( paramHolidaysSaveVO.getHolidayDate() );
        LambdaQueryWrapper< ParamHolidays > queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ParamHolidays::getCustomId,userInfoDetailVO.getCustomscode());
        if ( localDates.size() >  0) {
            queryWrapper.ge( ParamHolidays::getHolidayDate ,  localDates.get( 0 ) );
            queryWrapper.le( ParamHolidays::getHolidayDate ,  localDates.get(  localDates.size()-1 ) );
        }
        else {
            queryWrapper.eq( ParamHolidays::getHolidayDate , localDates.get( 0 ));
        }
        List< ParamHolidays > holidays = paramHolidaysRepository.list( queryWrapper );
        if ( !CollectionUtils.isEmpty( holidays ) ) {
            return BaseResult.failed( "该日期范围内有已经存在的节假日,请删除后操作" );
        }
        for ( LocalDate localDate : localDates ) {
            ParamHolidays paramHolidays = new ParamHolidays();
            paramHolidays.setRemark( paramHolidaysSaveVO.getRemark() );
            paramHolidays.setHolidayType( paramHolidaysSaveVO.getHolidayType() );
            paramHolidays.setHolidayDate( localDate );
            paramHolidays.setHolidayYear( ( long ) localDate.getYear() );
            paramHolidays.setCreateTime( LocalDateTime.now() );
            paramHolidays.setCreateBy( userInfoDetailVO.getUserId() );
            paramHolidays.setUpdateBy( userInfoDetailVO.getUserId() );
            paramHolidays.setUpdateTime( LocalDateTime.now() );
            paramHolidays.setCustomId(userInfoDetailVO.getCustomscode());
            paramHolidays.setHolidayType( paramHolidaysSaveVO.getHolidayType() );
            paramHolidays.setDelFlag( DeleteFlagEnum.NOT_DELETE.getValue() );
            paramHolidaysList.add( paramHolidays );
        }
        paramHolidaysRepository.saveBatch( paramHolidaysList );
        return BaseResult.ok( "保存成功" );
    }

    public List< LocalDate > getLocalDate( List< String > localDates ) {
        DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern( "yyyy-MM-dd" );
        LocalDate start = LocalDate.parse( localDates.get( 0 ).substring( 0 , 10 ) , ofPattern );
        LocalDate end = LocalDate.parse( localDates.get( 1 ).substring( 0 , 10 ) , ofPattern );
        long between = ChronoUnit.DAYS.between( start , end );
        List< LocalDate > allDates = new ArrayList<>();
        for ( long i = 0; i <= between; i++ ) {
            allDates.add( start.plusDays( i ) );
        }
        return allDates;
    }

    @Override
    public List< ParamHolidays > getAllHolidayDate( String year , String quarter ) {
        LambdaQueryWrapper< ParamHolidays > queryWrapper = new LambdaQueryWrapper<>();
        if ( quarter.equals( "1" ) ) {
            queryWrapper.eq( ParamHolidays::getHolidayYear , year ).and( wq -> {
                wq.like( ParamHolidays::getHolidayDate , year + "-01-" ).or().like( ParamHolidays::getHolidayDate ,
                        year + "-02-" ).or().like( ParamHolidays::getHolidayDate , year + "-03-" );
            } );
        }
        if ( quarter.equals( "2" ) ) {
            queryWrapper.eq( ParamHolidays::getHolidayYear , year ).and( wq -> {
                wq.like( ParamHolidays::getHolidayDate , year + "-04-" ).or().like( ParamHolidays::getHolidayDate ,
                        year + "-05-" ).or().like( ParamHolidays::getHolidayDate , year + "-06-" );
            } );
        }
        if ( quarter.equals( "3" ) ) {
            queryWrapper.eq( ParamHolidays::getHolidayYear , year ).and( wq -> {
                wq.like( ParamHolidays::getHolidayDate , year + "-07-" ).or().like( ParamHolidays::getHolidayDate ,
                        year + "-08-" ).or().like( ParamHolidays::getHolidayDate , year + "-09-" );
            } );
        }
        if ( quarter.equals( "4" ) ) {
            queryWrapper.eq( ParamHolidays::getHolidayYear , year ).and( wq -> {
                wq.like( ParamHolidays::getHolidayDate , year + "-10-" ).or().like( ParamHolidays::getHolidayDate ,
                        year + "-11-" ).or().like( ParamHolidays::getHolidayDate , year + "-12-" );
            } );
        }
        return paramHolidaysRepository.list( queryWrapper );
    }
}
